package com.zysc.processflow.common.maputil;

public class Line2D {
    private static final double RANGE = 0.1;//允许误差范围
    public Point2D startPoint = null;
    public Point2D endPoint = null;
    public int polygonLineIndex = -1;//-1表示不是polygonLine

    public double maxX = Double.MAX_VALUE;
    public double minX = Double.MIN_VALUE;
    public double maxY = Double.MAX_VALUE;
    public double minY = Double.MIN_VALUE;

    //直线一般式 ax+by+c = 0
    public double a;
    public double b;
    public double c;

    public Line2D(Point2D startPoint, Point2D endPoint) {
        this(startPoint, endPoint, 0);
    }

    /**
     * 线段，两点式
     * @param startPoint
     * @param endPoint
     */
    public Line2D(Point2D startPoint, Point2D endPoint, int polygonLineIndex) {
        this.startPoint=startPoint;
        this.endPoint=endPoint;
        this.polygonLineIndex=polygonLineIndex;
        this.minX=Math.min(startPoint.x,endPoint.x)-RANGE;//精度丢失
        this.maxX=Math.max(startPoint.x,endPoint.x)+RANGE;//精度丢失
        this.minY=Math.min(startPoint.y,endPoint.y)-RANGE;//精度丢失
        this.maxY=Math.max(startPoint.y,endPoint.y)+RANGE;//精度丢失

        double x1 = startPoint.x;
        double y1 = startPoint.y;
        double x2 = endPoint.x;
        double y2 = endPoint.y;

        this.a = y2 - y1;
        this.b = x1 - x2;
        this.c = (x2 - x1) * y1 - (y2 - y1) * x1;//或x2*y1-x1*y2
        if (this.b < 0) {
            this.a *= -1; this.b *= -1; this.c *= -1;
        }else if (b == 0 && a < 0) {
            this.a *= -1; this.c *= -1;
        }
    }

    //判断直线是否平行
    public boolean isParallel(Line2D line2D){
        double a1 = this.a;
        double b1 = this.b;
        double a2 = line2D.a;
        double b2 = line2D.b;
        double m = a1 * b2 - a2 * b1;
        return m == 0;
    }

    /**
     * 点是否在线段内
     * @param tPoint
     * @return
     */
    public boolean isIn(Point2D tPoint) {
        if (startPoint!=null&&endPoint!=null){
            Vector2D tVector = new Vector2D(tPoint.x - startPoint.x, tPoint.y - startPoint.y);
            Vector2D startVector = new Vector2D(endPoint.x - startPoint.x, endPoint.y - startPoint.y);
            double v = startVector.crossProduct(tVector);
            double yDis = Math.abs(v / startVector.getLength());
            if (yDis<RANGE){//tPoint在直线上
                if (contain(tPoint)){//tPoint在线段上
                    return true;
                }
            }
        }
        return false;
    }
    private boolean contain(Point2D point){
        return true;
    }
}
